package dev

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"net/http"
	"time"
)

// JWTSecret 是用于签名的密钥
var JWTSecret = []byte("hateys")

// GenerateJWT 生成一个JWT字符串
func GenerateJWT(userId string, username string) (string, error) {
	claims := jwt.MapClaims{
		"authorized": true,
		"userId":     userId,
		"username":   username,
		"exp":        time.Now().Add(1 * time.Hour).Unix(), // 设置过期时间为一天后
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(JWTSecret)
}

// ParseJWT 解析JWT字符串，并返回token中的claims
func ParseJWT(tokenString string) (*jwt.Token, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return JWTSecret, nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		expirationTime := claims["exp"].(float64)
		if time.Unix(int64(expirationTime), 0).Before(time.Now()) {
			return nil, fmt.Errorf("token is expired")
		}
	} else {
		return nil, fmt.Errorf("invalid token")
	}

	return token, nil
}

// CheckJWT 检验jwt
func CheckJWT(w http.ResponseWriter, r *http.Request) (bool, error) {
	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		return false, nil
	}

	tokenString := authHeader[len("Bearer "):]
	if len(tokenString) == 0 {
		http.Error(w, "无效的授权头", http.StatusUnauthorized)
		return false, nil
	}

	// 解析JWT
	_, err := ParseJWT(tokenString)
	if err != nil {
		http.Error(w, "JWT验证失败", http.StatusUnauthorized)
		return false, nil
	}
	return true, nil
}
